﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dimas.Framework.Common.Utils
{
    public static class Mapper
    {
        private static HashSet<int> dic=new HashSet<int>();
        
        public static D Map<S, D>(S obj) 
        {
            CreateMapper<S, D>();
            return AutoMapper.Mapper.Map<S, D>(obj);
        }

        public static IEnumerable<D> MapList<S, D>(IEnumerable<S> obj)
        {
            if (obj != null)
            {
                if (obj.Count() > 0)
                {
                    CreateMapper<S, D>();
                    var model = obj.ToList();
                    return AutoMapper.Mapper.Map<List<S>, List<D>>(model);
                }
            }
            return new List<D>();
        }

        private static void CreateMapper<S, D>()
        {
            int index = (typeof(S).MetadataToken.ToString() + typeof(D).MetadataToken.ToString()).GetHashCode();
            if (!dic.Contains(index))
            {
                AutoMapper.Mapper.CreateMap<S, D>();
                dic.Add(index);
            }
        }
    }
}
